
const User = require('../db/models/user')
// const Increase = require('../db/models/increase');
const { SuccessRes, ErrorRes } = require('../utils/res');
const { myHash, jwtSign } = require('../utils/util');
exports.register = async (ctx) => {
    let user = { username, password, phone } = ctx.request.body;
    const phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;
    if (!username || !password) {
        ctx.body = new ErrorRes({ code:401, message: '必填选项不能为空!' })
    } else if (!phoneReg.test(phone)) {
        ctx.body = new ErrorRes({ code:401, message: '手机号不正确!' })
    } else {
        let one = await User.find({ username: user.username });
        if (one.length == 0) {
            const New = new User(
                Object.assign(user, { password: myHash(user.password) })
            )
            let result = await New.save();
            return ctx.body = new SuccessRes({ result })
        } else {
            return ctx.body = new ErrorRes({ code:401, msg: '已存在相同用户!' })
        }
    }
}

exports.login = async (ctx) => {
    let user = { username, password, phone } = ctx.request.body;
    console.log('user--', user)
    const phoneReg = /^1(3|4|5|6|7|8|9)\d{9}$/;
    if (!username || !password) {
        ctx.body = new ErrorRes({ code:401, msg: '必填选项不能为空!' })
    } else if (!phoneReg.test(phone)) {
        ctx.body = new ErrorRes({ code:401, msg: '手机号不正确!' })
    } else {
        let users = await User.find({ username: user.username });
        let one = users[0]
        const hashPassword = myHash(user.password)
        if (one && hashPassword == one.password) {
            let userInfo = one.toAuthJSON();

            return ctx.body = new SuccessRes({ userInfo, token: jwtSign({ id: one._id }) })
        } else {
            return ctx.body = new ErrorRes({ code:401, msg: '登录失败!' })
        }
    }
}

exports.updateOne = async (ctx) => {
    let user = { id,username, phone, password, role, gender, age, avatar, content } = ctx.request.body;
    let authUser = await User.find({ _id:id });
    if (authUser.length == 0) {
        return ctx.body = new ErrorRes({ code:401, msg: `${username}不存在!` })
    } 
    await User.updateOne({ _id: id }, { $set: { username, phone, password, role, gender, age, avatar, content } })
    let result = Object.assign(authUser[0],user)
    return ctx.body = new SuccessRes({result}); 
}
exports.deleteOne = async(ctx)=>{
    let {id} = ctx.request.body;
    let authUser = await User.find({_id:id});
    if(authUser.length>0){
        let result = await User.deleteOne({_id:id})
        return ctx.body = new SuccessRes({result})
    }else{
        return ctx.body = new ErrorRes({ code:401, msg: `${authUser[0].username}不存在!` })
    }
}